package org.zoomdev.zoom.http;

import org.zoomdev.zoom.common.exceptions.ZoomException;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.security.KeyStore;

public class HttpClientBuilder {

    private int connectTimeout;
    private int readTimeout;
    private byte[] p12;
    private String password;

    public static HttpClientBuilder builder() {
        return new HttpClientBuilder();
    }

    private static X509TrustManager getDefaultX509TrustManager() throws Exception {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init((KeyStore) null);
        return (X509TrustManager) factory.getTrustManagers()[0];
    }

    /**
     * 设置连接超时(秒)
     *
     * @param connectTimeout 连接超时(秒)
     * @return
     */
    public HttpClientBuilder connectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
        return this;
    }

    /**
     * 设置读取超时(秒)
     *
     * @param readTimeout 读取超时(秒)
     * @return
     */
    public HttpClientBuilder readTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
        return this;
    }

    /**
     * 设置双向认证
     *
     * @param p12      p12证书加载的字节流
     * @param password 密码
     * @return
     */
    public HttpClientBuilder keystore(byte[] p12, String password) {
        assert (p12 != null);
        assert (password != null);
        this.p12 = p12;
        this.password = password;
        return this;
    }

    public HttpClient build() {
        if (p12 != null) {
            KeyStore keyStore = null;
            try {
                keyStore = KeyStore.getInstance("PKCS12");
                ByteArrayInputStream stream = new ByteArrayInputStream(p12);
                keyStore.load(stream, password.toCharArray());
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyManagerFactory.init(keyStore, password.toCharArray());
                SSLContext context = SSLContext.getInstance("TLSv1");
                context.init(keyManagerFactory.getKeyManagers(), null, null);
                return new DefaultOkHttpClient(connectTimeout, readTimeout, context.getSocketFactory(), getDefaultX509TrustManager());
            } catch (Exception e) {
                throw new ZoomException("创建双向认证客户端失败", e);
            }


        }
        return new DefaultOkHttpClient(connectTimeout, readTimeout);
    }
}
